let OSM = L.tileLayer.provider("OpenStreetMap.Mapnik");
let OPNVK = L.tileLayer.provider("OPNVKarte");
let OT = L.tileLayer.provider("OpenTopoMap");
let Dark = L.tileLayer.provider("Stamen.TonerBackground");
let Esri = L.tileLayer.provider("Esri.WorldTopoMap");

let baseMap = {
  tileLayer: OSM,
  OPNVKarte: OPNVK,
  OpenTopoMap: OT,
  "Stamen.TonerBackground": Dark,
  "Esri.WorldTopoMap": Esri,
};
// Create the map
let center = [39.93, 116.41];
let map = L.map("map", {
  center: center,
  zoom: 8,
  layers: [Esri],
});

// Set up the OSM layer
let mypLayers = L.control.layers(baseMap).addTo(map);

// add a marker in the given location

let drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
let editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);

let drawCircle, drawRectangle, drawPolygon, drawPolyLine;
let editCircle, editRectangle, editPolygon, editPolyLine;
let circleLatLng = [],
  rectanglePoint = [],
  polygonPoint = [],
  polylinePoint = [];
let circleLat, circleLng;
let distanceTotal = 0;
let r;
let editR = false,
  editC = false,
  editP = false,
  editPl = false;
let plArrow = [];
let distanceLatlngs = [];
var drawLocal = L.drawLocal;

function cancelDrawing() {
  drawnItems.eachLayer(function (layer) {
    drawnItems.removeLayer(layer);
  });
  map.off("draw:created");
}
function draw(type) {
  if (type === "circle") {
    if (!editC || circleLatLng != []) {
      removeLayerAll();
    }
    clearPoint();
    drawCircle = new L.Draw.Circle(map).enable();
    drawnItems.addLayer(drawCircle);
  } else if (type === "rectangle") {
    if (!editR || rectanglePoint != []) {
      removeLayerAll();
    }
    clearMarkers();
    clearPoint();
    drawRectangle = new L.Draw.Rectangle(map).enable();
    drawnItems.addLayer(drawRectangle);
  } else if (type === "polygon") {
    if (!editP || polygonPoint != []) {
      removeLayerAll();
    }
    clearMarkers();
    clearPoint();
    drawPolygon = new L.Draw.Polygon(map).enable();
    drawnItems.addLayer(drawPolygon);
  } else if (type === "polyLine") {
    if (!editPl) {
      // removeLayerAll();
    }
    distanceTotal = 0;
    clearMarkers();
    clearPoint();
    // clearCirclemarkers();
    drawPolyLine = new L.Draw.Polyline(map).enable();
    drawnItems.addLayer(drawPolyLine);
  }
}
function edit(type) {
  if (type === "circle") {
    editC = true;
    map.eachLayer(function (layer) {
      if (layer instanceof L.Circle) {
        map.removeLayer(layer);
      }
    });
    editCircle = L.circle(circleLatLng, r);
    editCircle.editing.enable();
    editableLayers.addLayer(editCircle);
  } else if (type === "rectangle") {
    editR = true;
    map.eachLayer(function (layer) {
      if (layer instanceof L.Rectangle) {
        map.removeLayer(layer);
      }
    });
    editRectangle = L.rectangle([rectanglePoint]);
    editRectangle.editing.enable();
    editableLayers.addLayer(editRectangle);
  } else if (type === "polygon") {
    editP = true;
    map.eachLayer(function (layer) {
      if (layer instanceof L.Polygon) {
        map.removeLayer(layer);
      }
    });
    editPolygon = new L.Polygon([polygonPoint]);
    editPolygon.editing.enable();
    editableLayers.addLayer(editPolygon);
    if (rectanglePoint !== []) {
      editRectangle = L.rectangle([rectanglePoint]);
      editableLayers.addLayer(editRectangle);
    }
  }
  // else if (type === "polyLine") {
  //   editPl = true;
  //   map.eachLayer(function (layer) {
  //     if (layer instanceof L.Polyline) {
  //       map.removeLayer(layer);
  //     }
  //   });
  //   editPolyLine = new L.Polyline([polylinePoint]);
  //   editPolyLine.editing.enable();
  //   editableLayers.addLayer(editPolyLine);
  //   getArrow(polylinePoint);
  // }
}

function save(type) {
  if (type === "circle") {
    editC = false;
    L.drawLocal.edit.toolbar.actions.save.title;
    editCircle.editing.disable();
  } else if (type === "rectangle") {
    editR = false;
    L.drawLocal.edit.toolbar.actions.save.title;
    editRectangle.editing.disable();
  } else if (type === "polygon") {
    editP = false;
    L.drawLocal.edit.toolbar.actions.save.title;
    editPolygon.editing.disable();
    // autoPolygon.editing.disable()
  }
  // else if (type === "polyLine") {
  //   editPl = false;
  //   L.drawLocal.edit.toolbar.actions.save.title;
  //   editPolyLine.editing.disable();
  //   getArrow(polylinePoint);
  // }
}

//鼠标右键事件
let body = document.body;
let contextMenu_ = $(".circleContextMenu")[0];
let polygonContextMenu_ = $(".polygonContextMenu")[0];
body.onclick = function () {
  contextMenu_.style.display = "none";
  polygonContextMenu_.style.display = "none";
};
let menu = document.getElementById("map");

// 绘制完成后触发
map.on("draw:created", function (e) {
  let type = e.layerType,
    layer = e.layer;
  drawnItems.addLayer(e.layer);
  if (type === "circle") {
    r = layer._mRadius;
    circleLatLng = [layer._latlng.lat, layer._latlng.lng];
    menu.oncontextmenu = function (e) {
      contextMenu_.style.display = "block";
      let left = e.pageX;
      let top = e.pageY;
      contextMenu_.style.left = left + "px";
      contextMenu_.style.top = top + "px";
      let changeR = document.getElementsByClassName("circleMenu")[0];
      changeR.onclick = function (e) {
        $("#lat").val(circleLatLng[0]);
        $("#lng").val(circleLatLng[1]);
        $("#raduis").val(r);
        $(".close-reveal-modal")[0].onclick = function () {
          circleLat = $("#lat").val();
          circleLng = $("#lng").val();
          circleLatLng = [Number(circleLat), Number(circleLng)];
          // console.log(circleLatLng);
          r = Number($("#raduis").val());
          //清除原有的图形
          //绘制圆心位置与半径
          map.eachLayer(function (layer) {
            if (layer instanceof L.Circle) {
              map.removeLayer(layer);
            }
          });
          editCircle = L.circle(circleLatLng, r);
          editableLayers.addLayer(editCircle);
          clearMarkers();
          showLable(circleLatLng[0], circleLatLng[1], r);
        };
      };
      return false;
    };
    clearMarkers();
    showLable(circleLatLng[0], circleLatLng[1], r);
  }
  if (type === "rectangle") {
    menu.oncontextmenu = function (e) {
      polygonContextMenu_.style.display = "none";
      return false;
    };
    rectanglePoint = layer._latlngs;
  }
  if (type === "polygon") {
    for (let i = 0; i < layer._latlngs[0].length; i++) {
      polygonPoint.push([layer._latlngs[0][i].lat, layer._latlngs[0][i].lng]);
    }
    menu.oncontextmenu = function (e) {
      if (type === "polygon") {
        polygonContextMenu_.style.display = "block";
        let left = e.pageX;
        let top = e.pageY;
        polygonContextMenu_.style.left = left + "px";
        polygonContextMenu_.style.top = top + "px";
        $(".polygonContextMenu")[0].onclick = function () {
          $(".polygonLatlngs").empty();
          for (let i = 0; i < polygonPoint.length; i++) {
            $(".polygonLatlngs")
              .append(`<div style="display: flex;justify-content: space-around;margin-top: 15px;">
                                                        <span class="pointNumber" style="width: 150px;display: inline-block;">点位${
                                                          i + 1
                                                        }:</span>
                                                        <input class="polygonLat" value="${
                                                          polygonPoint[i][0]
                                                        }" style="width: 230px;display: inline-block;margin-right: 10px;" />
                                                        <input class="polygonLng" value="${
                                                          polygonPoint[i][1]
                                                        }" style="width: 230px;display: inline-block;margin-right: 10px;" />
                                                     </div>`);
          }
        };
        $(".polygonSave")[0].onclick = function () {
          removeLayerAll();
          polygonPoint = [];
          for (let i = 0; i < $(".polygonLat").length; i++) {
            polygonPoint.push([
              Number($(".polygonLat").eq(i).val()),
              Number($(".polygonLng").eq(i).val()),
            ]);
          }
          editPolygon = new L.Polygon([polygonPoint]);
          // autoPolygon.editing.enable();
          editableLayers.addLayer(editPolygon);
        };
        return false;
      }
    };
  }
  if (type === "polyline") {
    menu.oncontextmenu = function (e) {
      polygonContextMenu_.style.display = "none";
      return false;
    };
    for (let i = 0; i < layer._latlngs.length; i++) {
      polylinePoint.push([layer._latlngs[i].lat, layer._latlngs[i].lng]);
      if (i < layer._latlngs.length - 1) {
        let distanceMarkerLatlng = L.latLng(
          layer._latlngs[i].lat,
          layer._latlngs[i].lng
        );
        distanceLatlngs.push([layer._latlngs[i].lat, layer._latlngs[i].lng]);
        getDistance(
          distanceMarkerLatlng,
          layer._latlngs[i],
          layer._latlngs[i + 1]
        );
      }

      getDistanceMarker(layer._latlngs[i]);
    }
    getDistanceTotal(polylinePoint[polylinePoint.length - 1]);
    // getDistanceTotalMarker(polylinePoint[polylinePoint.length - 1]);
    // getArrow(polylinePoint);
  }
});

// 修改圆和矩形大小触发
map.on("draw:editresize", function (e) {
  let layer = e.layer;
  type = e.layerType;
  clearMarkers();
  if (layer._mRadius) {
    r = layer._mRadius;
    showLable(e.layer._latlng.lat, e.layer._latlng.lng, r);
    circleLatLng = [layer._latlng.lat, layer._latlng.lng];
  } else if (layer._latlngs) {
    rectanglePoint = layer._latlngs;
  }
});
// 移动圆和矩形触发
map.on("draw:editmove", function (e) {
  let layer = e.layer;
  if (layer._mRadius) {
    r = layer._mRadius;
    circleLatLng = [Number(layer._latlng.lat), Number(layer._latlng.lng)];
    clearMarkers();
    showLable(circleLatLng[0], circleLatLng[1], r);
  } else if (layer._latlngs) {
    rectanglePoint = layer._latlngs;
  }
});
// 编辑多边形和线触发
map.on("draw:editvertex", function (e) {
  layer = e.layer;
  map.eachLayer(function (layer) {
    if (layer instanceof L.Polygon) {
      removeLayerAll();
      for (let i = 0; i < e.poly._latlngs[0].length; i++) {
        polygonPoint.push([
          e.poly._latlngs[0][i].lat,
          e.poly._latlngs[0][i].lng,
        ]);
      }
      editPolygon = new L.Polygon([polygonPoint]);
      editPolygon.editing.enable();
      editableLayers.addLayer(editPolygon);
    }
  });
  map.eachLayer(function (layer) {
    // if (layer instanceof L.Polyline) {
    //   // polylinePoint = [];
    //   // map.eachLayer(function (layer) {
    //   //   if (layer instanceof L.Polyline) {
    //   //     map.removeLayer(layer);
    //   //   }
    //   // });
    //   // for (let i = 0; i < e.poly._latlngs[0].length; i++) {
    //   //   polylinePoint.push([
    //   //     e.poly._latlngs[0][i].lat,
    //   //     e.poly._latlngs[0][i].lng,
    //   //   ]);
    //   // }
    //   // editPolyLine = new L.Polyline([polylinePoint]);
    //   // editPolyLine.editing.enable();
    //   // editableLayers.addLayer(editPolyLine);
    //   // getArrow(polygonPoint);
    //   // clearDistanceMarkers();
    //   // for (let i = 0; i < layer._latlngs[0].length; i++) {
    //   //   console.log(layer._latlngs[0][i]);
    //   //   if (i < layer._latlngs[0].length - 1) {
    //   //     let distanceMarkerLatlng = L.latLng(
    //   //       layer._latlngs[0][i].lat,
    //   //       layer._latlngs[0][i].lng
    //   //     );
    //   //     distanceLatlngs.push([
    //   //       layer._latlngs[0][i].lat,
    //   //       layer._latlngs[0][i].lng,
    //   //     ]);
    //   //     getDistance(
    //   //       distanceMarkerLatlng,
    //   //       layer._latlngs[0][i],
    //   //       layer._latlngs[0][i + 1]
    //   //     );
    //   //   }
    //   // }
    //   // map.dragging.disable();
    // }
  });
});

function clearPoint() {
  circleLatLng = [];
  rectanglePoint = [];
  polygonPoint = [];
  polylinePoint = [];
}
// 每次绘制前清除所有图层
function removeLayerAll() {
  map.eachLayer(function (layer) {
    if (
      layer instanceof L.Circle ||
      layer instanceof L.Polygon ||
      layer instanceof L.Rectangle ||
      layer instanceof L.Polyline
    ) {
      map.removeLayer(layer);
    }
    circleLatLng = [];
    rectanglePoint = [];
    polygonPoint = [];
    // polylinePoint = [];
  });
  clearMarkers();
  //清除线和标记
  clearDistanceMarkers();
  clearCirclemarkers();
  plArrow = [];
  multiCoords1 = [];
}
// 创建标记的坐标
let markers = [];
function showLable(lat, lng, r) {
  let markerLatLng = L.latLng(lat, lng);
  let marker = L.marker(markerLatLng, {
    draggable: false, // 不可拖动
    icon: L.divIcon({
      // 使用 divIcon 作为标记的图标
      className: "text-label-r", // 自定义 CSS 类名称
      html: `<h4 style="text-align:center;">半径${(r / 1000).toFixed(
        2
      )}公里</h4>`, // 设置文本标签内容
      iconSize: [150, 20], // 设置标记的大小
    }),
  });

  marker.addTo(map);
  markers.push(marker);
}

// 清除标记
function clearMarkers() {
  for (let i = 0; i < markers.length; i++) {
    map.removeLayer(markers[i]);
  }
  markers = [];
}

// 计算距离并添加标记
let distanceMarkers = [];
let textLatlng = [];
let distanceMarker;
let startText = [];
function getDistance(distanceMarkerLatlng, latlng1, latlng2) {
  distanceMarker = L.marker(distanceMarkerLatlng, {
    draggable: false, // 不可拖动
    icon: L.divIcon({
      // 使用 divIcon 作为标记的图标
      className: "text-label-r", // 自定义 CSS 类名称
      html: `<p style="font-weight: bold;text-align: center;font-size:16px;height:200px;-webkit-text-stroke:1px white;">${(
        map.distance(
          L.latLng(latlng1.lat, latlng1.lng),
          L.latLng(latlng2.lat, latlng2.lng)
        ) / 1000
      ).toFixed(2)}公里</p>`, // 设置文本标签内容
      iconSize: [150, 20], // 设置标记的大小
    }),
  });
  distanceMarker.addTo(map);
  distanceMarkers.push(distanceMarker);
  //计算总距离
  distanceTotal +=
    map.distance(
      L.latLng(latlng1.lat, latlng1.lng),
      L.latLng(latlng2.lat, latlng2.lng)
    ) / 1000;
  let polyline = L.polyline([latlng1, latlng2]).addTo(map);
  distanceMarker.setLatLng(polyline.getCenter());

  //标记起点
  // startText = L.marker(distanceLatlngs[0], {
  //   draggable: false,
  //   className: "text-label-r",
  //   icon: L.divIcon({
  //     iconSize: [0,0],
  //     html:'<p style="font-weight: bold;text-align: center;font-size:16px;-webkit-text-stroke:1px white;width: 100px;color:red;margin:-30px 20px 0 -20px;">起点</p>'
  //   }),
  // });
  // startText.addTo(map);
}

function clearDistanceMarkers() {
  for (let i = 0; i < distanceMarkers.length; i++) {
    map.removeLayer(distanceMarkers[i]);
  }
  distanceMarkers = [];
}

let circlemarkers = [];
function getDistanceMarker(latLng) {
  let circlemarker = new L.CircleMarker(latLng, {
    fillOpacity: 0.6,
    radius: 5,
    color: "red",
  }).addTo(map);
  circlemarker.addTo(map);
  circlemarkers.push(circlemarker);
}

function clearCirclemarkers() {
  for (let i = 0; i < circlemarkers.length; i++) {
    map.removeLayer(circlemarkers[i]);
  }
  circlemarkers = [];
}

// function getDistanceTotalMarker(latLng) {
//   let circlemarker = new L.CircleMarker(latLng, {
//     fillOpacity:.9,
//     color:'red',
//     zIndexOffset:1
//   }).addTo(map);
// }

//计算总距离
function getDistanceTotal(distanceMarkerLatlng) {
  let distanceMarker = L.marker(distanceMarkerLatlng, {
    draggable: false, // 不可拖动
    icon: L.divIcon({
      // 使用 divIcon 作为标记的图标
      className: "text-label-r", // 自定义 CSS 类名称
      html: `<p style="font-weight: bold; text-align: center;font-size:18px;height:200px;-webkit-text-stroke:1px white;">总长:${distanceTotal.toFixed(
        2
      )}公里</p>`, // 设置文本标签内容
      iconSize: [150, 20], // 设置标记的大小
    }),
  });
  distanceMarker.addTo(map);
  distanceMarkers.push(distanceMarker);
}

function getArrow(latLng) {
  let multiCoords1 = [latLng];
  for (let i = 0; i < multiCoords1.length; i++) {
    plArrow.push(L.polyline(multiCoords1[i]).addTo(map));
  }
  L.polylineDecorator(multiCoords1, {
    patterns: [
      {
        offset: 25,
        repeat: 50,
        symbol: L.Symbol.arrowHead({
          pixelSize: 15,
          pathOptions: { fillOpacity: 1, weight: 0 },
        }),
      },
    ],
  }).addTo(map);
}
